import React, { useState, useEffect } from 'react';
import { message } from 'antd';
import { useModel } from 'umi';
import ReactEChartsCore from 'echarts-for-react/lib/core';
import * as echarts from 'echarts/core';
import {
  // LineChart,
  BarChart,
  PieChart,
  // ScatterChart,
  // RadarChart,
  MapChart,
  // TreeChart,
  // TreemapChart,
  // GraphChart,
  // GaugeChart,
  // FunnelChart,
  // ParallelChart,
  // SankeyChart,
  // BoxplotChart,
  // CandlestickChart,
  // EffectScatterChart,
  // LinesChart,
  // HeatmapChart,
  // PictorialBarChart,
  // ThemeRiverChart,
  // SunburstChart,
  // CustomChart,
} from 'echarts/charts';
import {
  // GridSimpleComponent,
  GridComponent,
  // PolarComponent,
  // RadarComponent,
  // GeoComponent,
  // SingleAxisComponent,
  // ParallelComponent,
  // CalendarComponent,
  // GraphicComponent,
  ToolboxComponent,
  TooltipComponent,
  // AxisPointerComponent,
  // BrushComponent,
  TitleComponent,
  // TimelineComponent,
  // MarkPointComponent,
  // MarkLineComponent,
  // MarkAreaComponent,
  // LegendComponent,
  // LegendScrollComponent,
  // LegendPlainComponent,
  // DataZoomComponent,
  // DataZoomInsideComponent,
  // DataZoomSliderComponent,
  VisualMapComponent,
  // VisualMapContinuousComponent,
  // VisualMapPiecewiseComponent,
  AriaComponent,
  // TransformComponent,
  DatasetComponent,
} from 'echarts/components';
import { CanvasRenderer, SVGRenderer } from 'echarts/renderers';

import { SubjectData, ChartData } from '../data';
import { querySubjectData } from '../service';

import styles from '../index.less';

// import geoJson from '../geojson.json';

type FarmProps = {
  year: number;
  geoJson: { [key: string]: any };
};

const colors = ['#5289FF', '#52FFDC', '#0DEBFF', '#94BEFF'];

echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  BarChart,
  PieChart,
  MapChart,
  CanvasRenderer,
  SVGRenderer,
  ToolboxComponent,
  VisualMapComponent,
]);

const Farm: React.FC<FarmProps> = (props) => {
  const [ageData, setAgeData] = useState<ChartData[] | []>([]);
  const [averageAge, setAverageAge] = useState<ChartData>({});
  const [breedData, setBreedData] = useState<ChartData[] | []>([]);
  const [mapData, setMapData] = useState<ChartData[] | []>([]);
  const [resData, setResData] = useState<ChartData[] | []>([]);
  const [totalData, setTotalData] = useState<ChartData[] | []>([]);
  const [typeData, setTypeData] = useState<ChartData[] | []>([]);

  // 页面初始化
  useEffect(() => {}, []);

  useEffect(() => {
    // console.log(props.year);
    queryData(props.year);
  }, [props.year]);

  const { initialState } = useModel('@@initialState');

  // 数据查询
  const areaId = initialState?.currentUser?.areaId;
  const queryData = (year: number) => {
    querySubjectData({ year, areaId })
      .then((rsp: { code: number; msg: string; data: SubjectData }) => {
        if (rsp.code != 200) {
          message.error(rsp.msg);
          return;
        }
        const {
          ageData,
          averageAge,
          breedData,
          mapData,
          resData,
          totalData,
          typeData,
        } = rsp.data;
        setAgeData(ageData);
        setAverageAge(averageAge);
        setBreedData(breedData);
        setMapData(mapData);
        setResData(resData);
        setTotalData(totalData);
        setTypeData(typeData);

        // setBreedData([
        //   { dataTitle: '西门塔尔', dataValue: '101', adCode: null },
        //   { dataTitle: '海富特', dataValue: '202', adCode: null },
        //   { dataTitle: '安格斯', dataValue: '303', adCode: null },
        //   { dataTitle: '利木赞', dataValue: '404', adCode: null },
        // ]);
      })
      .catch((e) => console.log(e));
  };

  echarts.registerMap('MapChat', props.geoJson);

  // 地图
  const mapChart = (
    <ReactEChartsCore
      echarts={echarts}
      style={{ height: '100%' }}
      option={{
        // tooltip: {
        //   trigger: 'item',
        //   formatter: '{b}<br/>{c} (p / km2)',
        // },
        // toolbox: {
        //   show: true,
        //   orient: 'vertical',
        //   left: 'right',
        //   top: 'center',
        //   feature: {
        //     dataView: { readOnly: false },
        //     restore: {},
        //     saveAsImage: {},
        //   },
        // },
        series: [
          {
            name: '...',
            type: 'map',
            map: 'MapChat',
            left: 0,
            top: 0,
            right: 0,
            bottom: 0,
            itemStyle: {
              areaColor: 'rgba(255,255,255,0)',
              borderColor: '#43B4DF',
              borderWidth: 1.5,
            },
            label: {
              show: true,
              formatter: function (params) {
                return (
                  (params.data &&
                    [`{a|${params.data.value}}`, '{b| }'].join('\n')) ||
                  ''
                );
              },
              rich: {
                a: {
                  color: '#3BF2FF',
                  fontFamily: 'SF Pro Display Heavy Italic',
                  fontSize: 26,
                  fontWeight: 400,
                },
                b: {
                  backgroundColor: {
                    image: require('../../../assets/location2.gif'),
                  },
                  // lineHeight: 10,
                  height: 62,
                  width: 104,
                },
              },
            },
            data: mapData.map((d: ChartData) => ({
              value: d.dataValue,
              name: d.dataTitle,
            })),
          },
        ],
      }}
      notMerge={true}
      lazyUpdate={true}
      theme={'theme_name'}
      opts={{ renderer: 'svg' }}
    />
  );
  console.log(JSON.stringify(breedData));
  const bd = [
    { dataTitle: '西门塔尔', dataValue: '17895', adCode: null },
    { dataTitle: '海富特', dataValue: '321', adCode: null },
    { dataTitle: '安格斯', dataValue: '354', adCode: null },
    { dataTitle: '利木赞', dataValue: '1387', adCode: null },
    { dataTitle: '和牛  ', dataValue: '219', adCode: null },
    { dataTitle: '本地黄牛    ', dataValue: '1899', adCode: null },
  ];
  // 品种
  const breedChart = breedData.length > 0 && (
    <ReactEChartsCore
      echarts={echarts}
      option={{
        series: [
          {
            name: 'Area Breed',
            type: 'pie',
            radius: '50%',
            // roseType: 'radius',
            itemStyle: {
              color: '#22EAFF',
              shadowBlur: 200,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
            },
            label: {
              color: function (params) {
                console.log(params);
                return '#5BADC2';
              },
              formatter: ['{a|{b}}', '{b|{c}}'].join(''),
              rich: {
                a: {
                  color: '#5BADC2',
                },
                b: {
                  color: '#0DEBFF',
                  fontWeight: 800,
                  // height: 21,
                },
              },
            },
            labelLine: {
              lineStyle: {
                color: '#45ECFF',
              },
              smooth: 0.2,
              length: 6,
              length2: 10,
            },
            data: breedData
              .map((d: ChartData) => ({
                value: d.dataValue,
                name: d.dataTitle.trim(),
              }))
              .sort((a, b) => a.value - b.value),
          },
        ],
      }}
      style={{ height: 390, width: 420 }}
    />
  );

  // 类型
  const typeChart = typeData.length > 0 && (
    <ReactEChartsCore
      echarts={echarts}
      option={{
        series: [
          {
            name: 'Area Mode',
            type: 'pie',
            radius: '50%',
            // roseType: 'radius',
            itemStyle: {
              color: '#00FFBE',
              shadowBlur: 200,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
            },
            label: {
              color: '#5BADC2',
              formatter: ['{a|{b}}', '{b|{c}}'].join(''),
              rich: {
                a: {
                  color: '#5BADC2',
                },
                b: {
                  color: '#0DEBFF',
                  fontWeight: 800,
                  height: 21,
                },
              },
            },
            labelLine: {
              lineStyle: {
                color: '#45ECFF',
              },
              smooth: 0.2,
              length: 6,
              length2: 10,
            },
            data: typeData
              .map((d: ChartData) => ({
                value: d.dataValue,
                name: d.dataTitle,
              }))
              .sort((a, b) => a.value - b.value),
          },
        ],
      }}
      style={{ height: 390, width: 420 }}
    />
  );

  // 母牛
  const cowChart = ageData.length > 0 && (
    <ReactEChartsCore
      echarts={echarts}
      option={{
        title: {
          text: averageAge?.dataTitle,
          subtext: averageAge?.dataValue,
          left: 'center',
          top: '43%',
          textStyle: {
            color: '#48EAF0',
            fontSize: 14,
            fontWeight: 400,
          },
          subtextStyle: {
            color: '#0DEBFF',
            fontSize: 30,
            fontWeight: 800,
            height: 44,
          },
        },
        series: [
          {
            name: 'Area Cow',
            type: 'pie',
            radius: [50, 120],
            roseType: 'radius',
            itemStyle: {
              color: '#6BBFFF',
              shadowBlur: 200,
              shadowColor: 'rgba(0, 0, 0, 0.5)',
            },
            label: {
              color: '#5BADC2',
              formatter: ['{a|{b}}', '{b|{c}}'].join('\n'),
              rich: {
                a: {
                  color: '#5BADC2',
                },
                b: {
                  color: '#0DEBFF',
                  fontWeight: 800,
                  height: 21,
                },
              },
            },
            labelLine: {
              lineStyle: {
                color: '#45ECFF',
              },
              smooth: 0.2,
              length: 5,
              length2: 5,
            },
            data: ageData
              .map((d: ChartData) => ({
                value: d.dataValue,
                name: d.dataTitle,
              }))
              .sort((a, b) => a.value - b.value),
          },
        ],
      }}
      style={{ height: 390, width: 420 }}
    />
  );

  // 防疫
  const antiepidemicChart = resData.length > 0 && (
    <ReactEChartsCore
      echarts={echarts}
      option={{
        grid: {
          containLabel: true,
        },
        xAxis: {
          type: 'category',
          splitLine: {
            show: true,
            interval: 100,
            lineStyle: {
              color: '#5BADC2',
            },
          },
          axisLabel: {
            color: '#48EAF0',
            fontSize: 14,
            margin: 13,
          },
          axisLine: {
            lineStyle: {
              color: '#5BADC2',
            },
          },
          data: resData.map((d: ChartData) => d.dataTitle),
        },
        yAxis: {
          type: 'value',
          name: '总数',
          nameTextStyle: {
            color: '#48EAF0',
            align: 'right',
          },
          splitLine: {
            show: false,
            lineStyle: {
              color: '#5BADC2',
            },
          },
          axisLabel: {
            color: '#5BADC2',
            fontSize: 14,
            margin: 15,
          },
        },
        series: [
          {
            label: {
              show: true,
              position: 'top',
              color: '#0DEBFF',
            },
            // barWidth: 80,
            data: resData.map((d: ChartData, index: number) => ({
              value: d.dataValue,
              itemStyle: { color: colors[index] },
            })),
            type: 'bar',
          },
        ],
      }}
      style={{ height: 400, width: 414 }}
    />
  );

  return (
    <>
      {/* 标题 */}
      <div className={styles.header}>
        <div className={styles.title}>
          区域：{initialState?.currentUser?.areaName}
        </div>
      </div>

      {/* 总数 */}
      <div className={styles.countContainer + ' ' + styles.layout}>
        {totalData.map((d: ChartData, index: number) => (
          <div key={index} className={styles.countItem}>
            <div className={styles.countTitle}>{d.dataTitle}</div>
            <div className={styles.countNum}>{d.dataValue}</div>
            <img
              className={styles.countBg}
              src={require('../../../assets/count-bg.png')}
            />
          </div>
        ))}
      </div>

      {/* 地图 */}
      <div className={styles.mapContainer + ' ' + styles.layout}>
        <div className={styles.mapTitle}>
          <img
            className={styles.mapTitleImg}
            src={require('../../../assets/title-left.png')}
          />
          <div className={styles.mapTitleLable}>单件：牛只数/养殖户数</div>
          <img
            className={styles.mapTitleImg}
            src={require('../../../assets/title-right.png')}
          />
        </div>
        {mapChart}
      </div>

      {/* 左边 */}
      <div className={styles.left + ' ' + styles.layout}>
        <div className={styles.leftCard}>
          <div className={styles.cardTitle}>品种</div>
          {breedChart}
        </div>
        <div className={styles.leftCard}>
          <div className={styles.cardTitle}>类型</div>
          {typeChart}
        </div>
      </div>

      {/* 右边 */}
      <div className={styles.right + ' ' + styles.layout}>
        <div className={styles.rightCard}>
          <div className={styles.cardTitle}>母牛</div>
          {cowChart}
        </div>
        <div className={styles.rightCard}>
          <div className={styles.cardTitle}>2022年防疫</div>
          {antiepidemicChart}
        </div>
      </div>
    </>
  );
};

export default Farm;
